package net.cyl.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
// 添加日志记录功能
@Slf4j
public class RabbitMQErrorConfig {
    /**
     * 错误队列配置
     */


    // 定义错误交换机
    private String shortLinkErrorExchange = "short_link.error.exchange";

    // 定义错误队列
    private String shortLinkErrorQueue = "short_link.error.queue";

    // 定义错误路由键
    private String shortLinkErrorRoutingKey = "short_link.error.routing.key";
    @Autowired
    private RabbitTemplate rabbitTemplate;
    /**
     * 声明错误交换机（Dead Letter Exchange）
     */


    @Bean
    public TopicExchange errorExchange() {
        return new TopicExchange(shortLinkErrorExchange, true, false);
    }

    /**
     * 声明错误队列（Dead Letter Queue）
     */
    @Bean
    public Queue errorQueue() {
        return new Queue(shortLinkErrorQueue, true);
    }

    /**
     * 将错误队列绑定到错误交换机
     */
    @Bean
    public Binding errorBinding() {
        return BindingBuilder.bind(errorQueue()).to(errorExchange()).with(shortLinkErrorRoutingKey);
    }
    /**
     * 消息重试配置
     */
    @Bean
    public MessageRecoverer messageRecoverer() {
        return new RepublishMessageRecoverer(rabbitTemplate, shortLinkErrorExchange, shortLinkErrorRoutingKey);
    }
}
